/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 *
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.service.ReportCopyRecordService;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.MathUtil;
import com.yixun.qfbao.util.PageUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.PremisesRecommender;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.dto.FollowUpListDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.CommissionStatusEnum;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.FollowUpListService;
import com.yixun.qfbao.xf.service.PremisesService;
import com.yixun.qfbao.xf.service.impl.CustomerPremisesServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AssistantReportServiceImpl implements AssistantReportService {

    @Autowired
    PartnerInfoService partnerInfoService;
    @Autowired
    RoleResourcesService roleResourcesService;
    @Autowired
    ReportCopyRecordService reportCopyRecordService;
    @Autowired
    PremisesPermissionService premisesPermissionService;
    @Autowired
    DeptPermissionService deptPermissionService;
    @Autowired
    DataCenterService dataCenterService;
    @Autowired
    PremisesRecommenderService premisesRecommenderService;
    @Autowired
    EstateAdviserService estateAdviserService;
    @Autowired
    CustomerPremisesService customerPremisesService;
    @Autowired
    CompanyRelationService companyRelationService;
    @Autowired
    DepartmentDao departmentDao;
    @Autowired
    PremisesService premisesService;

    @Override
    public AssistantReportPageResDto getAssistantReportPage(AssistantReportPageReqDto reqDto) {
        AssistantReportPageResDto resDto = new AssistantReportPageResDto();
        resDto.setResult(ResultEnum.FAIL.getNo());
        if(StringUtils.isBlank(reqDto.getUserId())){
            resDto.setCpDtoPage(null);
            return resDto;
        }
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        if (Objects.isNull(partnerInfo)) {
            resDto.setResult(ResultEnum.USER_IS_NULL.getNo());
            resDto.setResultMsg(ResultEnum.USER_IS_NULL.getDes());
            return resDto;
        }

        buildCommonCondition(reqDto, partnerInfo);
        Page<CustomerPremisesDto> cpDtoPage = getAssistantReportPage(reqDto, partnerInfo);
        // 统计所有报备被复制的次数
        List<CustomerPremisesDto> rows = cpDtoPage.getRows();
        if (CollectionUtils.isNotEmpty(rows)) {
            List<Long> reportIds = rows.stream().map(CustomerPremisesDto::getId).collect(Collectors.toList());
            ReportCopyRecordDto rcrDto = new ReportCopyRecordDto();
            rcrDto.setCopyUser(Long.valueOf(reqDto.getUserId()));
            rcrDto.setReportIds(reportIds);
            List<ReportCopyRecordDto> rcrDtoList = reportCopyRecordService.selectCopyCountByReport(rcrDto);
            Map<Long, Integer> rcrDtoMap = rcrDtoList.stream().collect(Collectors.toMap(ReportCopyRecordDto::getReportId, ReportCopyRecordDto::getCopyCount, (oldValue, newValue) -> newValue));
            rows.forEach(item -> {
                Integer copyCount = rcrDtoMap.get(item.getId());
                item.setCopyCount(0);
                if(Objects.nonNull(copyCount)){
                    item.setCopyCount(copyCount);
                }
            });
            cpDtoPage.setRows(rows);
        }
        resDto.setCpDtoPage(cpDtoPage);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

    @Override
    public AssistantReportPageResDto getAssistantAppReportPage(AssistantReportPageReqDto reqDto) {
        AssistantReportPageResDto resDto = new AssistantReportPageResDto();
        resDto.setResult(ResultEnum.FAIL.getNo());
        if(StringUtils.isBlank(reqDto.getUserId())){
            resDto.setCpDtoPage(null);
            return resDto;
        }
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        if (Objects.isNull(partnerInfo)) {
            resDto.setResult(ResultEnum.USER_IS_NULL.getNo());
            resDto.setResultMsg(ResultEnum.USER_IS_NULL.getDes());
            return resDto;
        }
        buildCommonCondition(reqDto, partnerInfo);
        Page<CustomerPremisesDto> cpDtoPage = getAssistantAppReportPage(reqDto, partnerInfo);
        // 统计所有报备被复制的次数
        List<CustomerPremisesDto> rows = cpDtoPage.getRows();
        if (CollectionUtils.isNotEmpty(rows)) {
            List<Long> reportIds = rows.stream().map(CustomerPremisesDto::getId).collect(Collectors.toList());
            ReportCopyRecordDto rcrDto = new ReportCopyRecordDto();
            rcrDto.setCopyUser(Long.valueOf(reqDto.getUserId()));
            rcrDto.setReportIds(reportIds);
            List<ReportCopyRecordDto> rcrDtoList = reportCopyRecordService.selectCopyCountByReport(rcrDto);
            Map<Long, Integer> rcrDtoMap = rcrDtoList.stream().collect(Collectors.toMap(ReportCopyRecordDto::getReportId, ReportCopyRecordDto::getCopyCount, (oldValue, newValue) -> newValue));
            rows.forEach(item -> {
                Integer copyCount = rcrDtoMap.get(item.getId());
                item.setCopyCount(0);
                if(Objects.nonNull(copyCount)){
                    item.setCopyCount(copyCount);
                }
            });
            cpDtoPage.setRows(rows);
        }

        resDto.setCpDtoPage(cpDtoPage);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

    private void buildCommonCondition(AssistantReportPageReqDto reqDto, PartnerInfo partnerInfo){
        reqDto.setAccountType(partnerInfo.getAccountType());
        reqDto.setMerchantId(partnerInfo.getHigherid());
        switch (reqDto.getCustomerStatus() == null ? " " : reqDto.getCustomerStatus()) {
            case "a":
                reqDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                reqDto.setDisableType(DisableTypeEnum.report_invalid.getNo());
                break;
            case "b":
                reqDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                reqDto.setDisableType(DisableTypeEnum.visit_invalid.getNo());
                break;
            default:
                break;
        }
        switch (reqDto.getConfirmStatus() == null ? " " : reqDto.getConfirmStatus()) {
            case "A":
                reqDto.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                reqDto.setDisableType(DisableTypeEnum.PAYDEPOSIT_FAILD.getNo());
                break;
            case "B":
                reqDto.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                reqDto.setDisableType(DisableTypeEnum.SUBSCRIBE_FAILD.getNo());
                break;
            case "C":
                reqDto.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                reqDto.setDisableType(DisableTypeEnum.SIGN_FAILD.getNo());
                break;
            default:
                break;
        }
        Map<String, Object> ruleMap = getRoleResourcesPermission(reqDto.getLoginType(), partnerInfo.getUserRoleId(), partnerInfo.getAccountType());
        if(Objects.nonNull(ruleMap)){
            if(ruleMap.containsKey("showFullNumber") && Objects.nonNull(ruleMap.get("showFullNumber"))){
                reqDto.setShowFullNumber((Boolean) ruleMap.get("showFullNumber"));
            }
            if(ruleMap.containsKey("hideAgentPhone") && Objects.nonNull(ruleMap.get("hideAgentPhone"))){
                reqDto.setHideAgentPhone((Boolean) ruleMap.get("hideAgentPhone"));
            }
            if(ruleMap.containsKey("roleReportWay") && Objects.nonNull(ruleMap.get("roleReportWay"))){
                reqDto.setRoleReportWay(String.valueOf(ruleMap.get("roleReportWay")));
            }
        }
    }

    private Map<String, Object> getRoleResourcesPermission(String loginType, Long roleId, String accountType) {
        Map<String, Object> ruleMap = new HashMap<>();
        if (StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), loginType) ||
            StringUtils.equals(SystemIdEnum.ASSISTANT.getCode(), loginType)) {
            // 去除游客
            if (roleId != null && roleId != 0L && roleId != -1L) {
                // menu_0005_0001_0013: 查看隐号报备
                // menu_0005_0001_0014: 查看全号报备
                // menu_0005_0001_0015: 客户号码隐藏中间4位
                // menu_0005_0001_0020: 经纪人号码隐藏中间四位
                // menu_0008_0006: 客户号码隐藏中间4位
                // menu_0008_0007: 经纪人号码隐藏中间四位
                List<String> codes = Lists.newArrayList();
                codes.add("menu_0005_0001_0013");
                codes.add("menu_0005_0001_0014");
                codes.add("menu_0005_0001_0015");
                codes.add("menu_0005_0001_0020");
                codes.add("menu_0008_0006");
                codes.add("menu_0008_0007");
                List<RoleResources> roleResources = roleResourcesService.listRoleResources(roleId, codes);
                // 0: 全部 1: 全号 2: 隐号
                int temp = 0;
                boolean show = true;
                boolean hideAgentPhone = false;
                if (roleResources != null && roleResources.size() > 0) {
                    for (RoleResources roleResource : roleResources) {
                        if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0013")) {
                            temp += 2;
                        } else {
                            temp += 1;
                        }
                        if (loginType.equals(SystemIdEnum.DEVELOPERS.getCode())) {
                            if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0015")) {
                                show = false;
                            }
                            if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0020")) {
                                hideAgentPhone = true;
                            }
                        } else if (loginType.equals(SystemIdEnum.ASSISTANT.getCode()) ||
                                loginType.equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
                            if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0008_0006")) {
                                show = false;
                            }
                            if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0008_0007")) {
                                hideAgentPhone = true;
                            }
                        }
                    }
                }
                // 超级管理不受权限控制
                if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(accountType)) {
                    ruleMap.put("showFullNumber", show);
                    ruleMap.put("hideAgentPhone", hideAgentPhone);
                }
                ruleMap.put("roleReportWay", temp);
            }
        }
        return ruleMap;
    }

    private Page<CustomerPremisesDto> getAssistantReportPage(AssistantReportPageReqDto reqDto, PartnerInfo partnerInfo) {
        CustomerPremisesDto entity = new CustomerPremisesDto();
        Map<String, Integer> map = PageUtil.getPageInfo(reqDto.getPageNo(), reqDto.getPageSize());
        // 构建当前登录人可查看楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
        if(CollectionUtils.isEmpty(premisesIds)){
            entity.setAuthorityPremisesIds(Arrays.asList(-1L));
        }else{
            entity.setAuthorityPremisesIds(premisesIds);
        }

        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
        entity.setAgencyDeptIds(deptPermissionList);
        // 判断是否指定楼盘检索
        if (StringUtils.isNotBlank(reqDto.getPremisesId())) {
            entity.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
        } else {
            entity.setPremisesId(null);
            // 渠道经理所属经纪人
            List<List<Long>> staffIds = dataCenterService.getStaffIdsByPrincipal(Long.valueOf(reqDto.getUserId()));
            if (CollectionUtils.isNotEmpty(staffIds)) {
                entity.setPrincipalStaffIds(staffIds);
            }
        }
        if (!StringUtils.isEmpty(reqDto.getCustomerStatus())) {
            entity.setCustomerStatus(reqDto.getCustomerStatus());
        }
        if (!StringUtils.isEmpty(reqDto.getConfirmStatus())) {
            entity.setConfirmStatus(reqDto.getConfirmStatus());
        }
        //失败类型
        if (!StringUtils.isEmpty(reqDto.getDisableType())) {
            entity.setDisableType(reqDto.getDisableType());
        }

        if (!StringUtils.isEmpty(reqDto.getTimeType())) {
            entity.setTimeType(reqDto.getTimeType());
        }
        if (!StringUtils.isEmpty(reqDto.getCreateTimeBefore())) {
            String before = reqDto.getCreateTimeBefore() + " 00:00:00";
            entity.setCreateTimeBefore(DateUtils.StringToDate(before, DateStyle.YYYY_MM_DD_HH_MM_SS));
        }
        if (!StringUtils.isEmpty(reqDto.getCreateTimeAfter())) {
            String after = reqDto.getCreateTimeAfter() + " 23:59:59";
            entity.setCreateTimeAfter(DateUtils.StringToDate(after, DateStyle.YYYY_MM_DD_HH_MM_SS));
        }
        if (StringUtils.isNotBlank(reqDto.getReportUserType())) {
            entity.setReportUserType(reqDto.getReportUserType());
        }
        if (StringUtils.isNotEmpty(reqDto.getVisitState())) {
            entity.setVisitState(reqDto.getVisitState());
        }
        // 按部门查询,包含查询部门下级
        if(StringUtils.isNotBlank(reqDto.getAgentId())){
            entity.setStaffId(Long.valueOf(reqDto.getAgentId()));
        }
        if (StringUtils.isNotBlank(reqDto.getCompanyId())) {
            entity.setStaffCompanyId(Long.valueOf(reqDto.getCompanyId()));
        }
        if(Objects.nonNull(reqDto.getAgencyDeptId()) && StringUtils.isBlank(reqDto.getAgentId())){
            List<Department> deptList = departmentDao.getChildDeptListByDeptId(reqDto.getAgencyDeptId());
            List<Long> searchDeptIds = deptList.stream().map(Department::getId).collect(Collectors.toList());
            entity.setSearchDeptIds(searchDeptIds);
        }
        // 推荐人查询
        if (reqDto.getRecommenderId() != null) {
            List<PremisesRecommender> premisesRecommenders = premisesRecommenderService.selectPremisesRecommenderById(reqDto.getRecommenderId());
            List<String> recommenderUuids = premisesRecommenders.stream().map(item -> item.getRecommenderUuid()).collect(Collectors.toList());
            entity.setRecommenderUuids(recommenderUuids);
        }
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            entity.setAdviserUuids(adviserUuids);
        }
        entity.setCompanyId(partnerInfo.getHigherid());
        if (StringUtils.isNotBlank(reqDto.getRoleReportWay())) {
            entity.setRoleReportWay(reqDto.getRoleReportWay());
        }
        if (reqDto.getCanViewPartnerIds() != null && reqDto.getCanViewPartnerIds().size() > 0) {
            entity.setCanViewPartnerIds(reqDto.getCanViewPartnerIds());
        }
        if (StringUtils.isNotEmpty(reqDto.getName())) {
            entity.setName(reqDto.getName());
        }
        if (reqDto.getShowFullNumber() != null && Boolean.FALSE.equals(reqDto.getShowFullNumber())) {
            entity.setShowFullNumber(Boolean.FALSE);
        }
        entity.setHideAgentPhone(reqDto.getHideAgentPhone());
        if (StringUtils.isNotBlank(reqDto.getMortgageStatus())) {
            entity.setMortgageStatus(reqDto.getMortgageStatus());
        }
        if (StringUtils.isNotBlank(reqDto.getPayFinish())) {
            entity.setPayFinish(reqDto.getPayFinish());
        }
        entity.setOrders(" t.create_time desc");
        log.info("getAssistantReportPage userId: {}, params: {}", reqDto.getUserId(), JSONObject.toJSONString(entity));
        Page<CustomerPremisesDto> cpDtoPage = customerPremisesService.getMyPageModel2(entity, map.get("startRow"), map.get("endRow"));
        cpDtoPage.setPageNumber(reqDto.getPageNo());
        cpDtoPage.setTotalPages(com.yixun.qfbao.util.PageUtil.getTotalPage(new Integer(cpDtoPage.getTotal() + ""), reqDto.getPageSize()));
        cpDtoPage.setPageSize(reqDto.getPageSize());
        return cpDtoPage;
    }

   
    
    private Page<CustomerPremisesDto> getAssistantAppReportPage(AssistantReportPageReqDto reqDto, PartnerInfo partnerInfo) {
        CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
        if(StringUtils.isNotBlank(reqDto.getPremisesId())) {
            cusPreDto.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
        }
        // 判断用户被指定楼盘是否为临时权限(目前只有置业顾问是临时权限)
        List<Long> premisesPermission = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
        if(CollectionUtils.isEmpty(premisesPermission)) {
            cusPreDto.setAuthorityPremisesIds(Arrays.asList(-1L));
        }else {
            cusPreDto.setAuthorityPremisesIds(premisesPermission);
        }
        // 如果传递需要查询全部，则不以传入楼盘为标准查询
        if(reqDto.getAllPremisesFlag() != null && !reqDto.getAllPremisesFlag()) {
        	if(CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
                cusPreDto.setPremisesIds(reqDto.getPremisesIds());
            }else {
                cusPreDto.setPremisesIds(Arrays.asList(-1L));
            }
        }
        

        String customerStatus = reqDto.getCustomerStatus();
        if(StringUtils.isNotBlank(customerStatus)){
            String statusArr[] = customerStatus.split("[,]");
            List<String> statusList = new ArrayList<String>();
            for (int ii = 0; ii < statusArr.length; ii++) {
                if (StringUtils.isNotEmpty(statusArr[ii])) {
                    statusList.add(statusArr[ii]);
                }
            }
            if (statusList.size() > 0) {
                cusPreDto.setCustomerStatusList(statusList);
            }
        }

        String confirmStatus = reqDto.getConfirmStatus();
        if (StringUtils.isNotBlank(confirmStatus)) {
            cusPreDto.setConfirmStatus(confirmStatus);
        }
        cusPreDto.setSearchContent(reqDto.getName());
        if (StringUtils.isNotBlank(reqDto.getRoleReportWay())) {
            cusPreDto.setRoleReportWay(reqDto.getRoleReportWay());
        }
        if (reqDto.getCanViewPartnerIds() != null && reqDto.getCanViewPartnerIds().size() > 0) {
            cusPreDto.setCanViewPartnerIds(reqDto.getCanViewPartnerIds());
        }
        if (reqDto.getShowFullNumber() != null && Boolean.FALSE.equals(reqDto.getShowFullNumber())) {
            cusPreDto.setShowFullNumber(Boolean.FALSE);
        }

        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            cusPreDto.setAdviserUuids(adviserUuids);
        }

        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
        cusPreDto.setAgencyDeptIds(deptPermissionList);
        cusPreDto.setOrders("create_time desc");
        log.info("getAssistantAppReportPage userId: {}, params: {}", reqDto.getUserId(), JSONObject.toJSONString(cusPreDto));
        CustomerPremisesServiceImpl.LOGIN_TYPE.set(reqDto.getLoginType());
        Page<CustomerPremises> cusPrePage = customerPremisesService.getPageModel(cusPreDto,
                com.yixun.common.page.PageUtil.begin(reqDto.getPageNo(), reqDto.getPageSize()),
                reqDto.getPageSize());
        Page<CustomerPremisesDto> customerPremisesDtoPage = new Page<>();
        List<CustomerPremisesDto> dtoList = new ArrayList<>();
        List<CustomerPremises> rows = cusPrePage.getRows();
        List<Long> premisesIds = rows.stream().map(CustomerPremises::getPremisesId).collect(Collectors.toList());
        premisesIds = premisesIds.stream().distinct().collect(Collectors.toList());
        PremisesDto preDto = new PremisesDto();
        preDto.setName(reqDto.getName());
        preDto.setPremisesIds(premisesIds);
        List<Premises> premisesList = premisesService.selectIdListByDto(preDto);
        Map<Long, String> completeNodeMap = premisesList.stream().collect(Collectors.toMap(Premises::getId, item -> StringUtils.defaultIfBlank(item.getCompleteNode(), StringUtils.EMPTY), (oldData, newData) -> newData));
        for (CustomerPremises customerPremises : rows) {
            Map<String, String> map = customerPremisesService.getCusStatus(customerPremises);
            customerPremises.setCurrentStatus(map.get("currentStatus"));
            CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
            BeanUtils.copyProperties(customerPremises, customerPremisesDto);
            customerPremisesDto.setCompleteNode(completeNodeMap.get(customerPremises.getPremisesId()));
            if(Objects.nonNull(customerPremises.getHopeVisitTime())){
                customerPremisesDto.setFormatHopeVisitTime(DateUtils.DateToString(customerPremises.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            }
            if(Objects.nonNull(reqDto.getHideAgentPhone()) && Boolean.TRUE.equals(reqDto.getHideAgentPhone())){
                customerPremisesDto.setStaffPhone(ReportWayEnum.convertMobileByReportWay(customerPremisesDto.getStaffPhone(), ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo()));
            }
            dtoList.add(customerPremisesDto);
        }
        customerPremisesDtoPage.setRows(dtoList);
        customerPremisesDtoPage.setPageNumber(reqDto.getPageNo());
        // 总条数/pageSize 向上取整
        int totalPages = (int) Math.ceil(new Double(cusPrePage.getTotal()) / reqDto.getPageSize().doubleValue());
        customerPremisesDtoPage.setTotalPages(totalPages);
        customerPremisesDtoPage.setPageSize(reqDto.getPageSize());
        return customerPremisesDtoPage;
    }

    /**
     * 构建机构/门店组别/分销经纪人查询条件
     * @param reqDto
     */
    private void buildDeptOrPartnerCondition(CustomerPremisesDto entity, AssistantReportPageReqDto reqDto, PartnerInfo partnerInfo) {
        if (StringUtils.isNotEmpty(reqDto.getAgentId())) {
            entity.setStaffId(Long.valueOf(reqDto.getAgentId()));
            return;
        }
        if (reqDto.getStoreOrGroupId() != null) {
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setId(reqDto.getStoreOrGroupId());
            if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo())) {
                CompanyRelationDto companyRelationDto = new CompanyRelationDto();
                companyRelationDto.setDevCompany(partnerInfo.getHigherid());
                List<CompanyRelation> crList = companyRelationService.selectListByDto(companyRelationDto);
                if (crList != null && crList.size() > 0) {
                    List<Long> agenceIdList = crList.stream().map(CompanyRelation::getAgentCompany).collect(Collectors.toList());
                    departmentDto.setMerchantIds(StringUtils.join(agenceIdList, ","));
                }
            }
            List<Department> deptList = departmentDao.selectListByDto(departmentDto);
            if (null != deptList && deptList.size() > 0) {
                List<Long> deptIds = deptList.stream().map(Department::getId).collect(Collectors.toList());
                List<Long> deptIdsTemp = new ArrayList<>();
                for (Long deptId : deptIds) {
                    deptIdsTemp.addAll(listDepartmentByParentId(deptId));
                }
                if (deptIdsTemp != null && deptIdsTemp.size() > 0) deptIds.addAll(deptIdsTemp);
                PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
                partnerInfoDto.setDeptIds(deptIds);
                List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(partnerInfoDto);
                if (null != partnerInfoList && partnerInfoList.size() > 0) {
                    List<Long> partnerIds = partnerInfoList.stream().map(PartnerInfo::getId).collect(Collectors.toList());
                    entity.setPartnerIds(partnerIds);
                }
            }
            return;
        }
        if (!StringUtils.isEmpty(reqDto.getCompanyId())) {
            entity.setStaffCompanyId(Long.valueOf(reqDto.getCompanyId()));
        }
    }

    private List<Long> listDepartmentByParentId(Long deptId) {
        List<Long> list = new ArrayList<>();
        DepartmentDto department = new DepartmentDto();
        department.setParentId(deptId);
        List<Department> departmentList = departmentDao.selectListByDto(department);
        list.add(deptId);
        if (departmentList != null && departmentList.size() > 0) {
            for (Department dept : departmentList) {
                list.addAll(listDepartmentByParentId(dept.getId()));
            }
        }
        return list;
    }
}
